using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text;

namespace CoreCalc.SheetDefinedFunctions
{
    public class LocalBuilderPool<T>
    {
        private Queue<LocalBuilder> pool;
        private int totalNumberOfItems;
        private ILGenerator ilg;

        public LocalBuilderPool(int initialSize, ILGenerator ilg)
        {
            totalNumberOfItems = 0;
            this.ilg = ilg;
            pool = new Queue<LocalBuilder>(initialSize);
            PopulatePool(initialSize);
        }

        private void PopulatePool(int numberOfItems)
        {
            for (int i = 0; i < numberOfItems; i++)
            {
                pool.Enqueue(ilg.DeclareLocal(typeof(T)));
            }
            totalNumberOfItems += numberOfItems;
        }

        public LocalBuilder GetVariable()
        {
            if(pool.Count == 0)
            {
                PopulatePool(totalNumberOfItems);
                // Console.WriteLine("Growing {0} locals pool to {1}", typeof(T), totalNumberOfItems);
            }
            return pool.Dequeue();
        }

        public void ReleaseVariable(params LocalBuilder[] lb)
        {
            foreach (LocalBuilder builder in lb)
            {
                pool.Enqueue(builder);
            }
        }
    }
}
